/**
 * Created by jiachenpan on 16/11/18.
 */

export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

//判断是否是iphoneX系列
export function isIphonex() {
  // X XS, XS Max, XR
  const xSeriesConfig = [
    {
    devicePixelRatio: 3,
    width: 375,
    height: 812,
    },
    {
    devicePixelRatio: 3,
    width: 414,
    height: 896,
    },
    {
    devicePixelRatio: 2,
    width: 414,
    height: 896,
    },
  ];

  // h5
 if (typeof window !== 'undefined' && window) {
  const isIOS = /iphone/gi.test(window.navigator.userAgent);
  if (!isIOS) return false;
  const { devicePixelRatio, screen } = window;
  const { width, height } = screen;
  return xSeriesConfig.some(item => item.devicePixelRatio === devicePixelRatio && item.width === width && item.height === height);
  }
  return false;
}

//判断设备
export function getSystemType() {
  var res = {};
  var userAgent = navigator.userAgent;
  var isAndroid = userAgent.indexOf('Android') > -1 || userAgent.indexOf('Adr') > -1; //android终端
  var isiOS = !!userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
  
  if (isAndroid) {
    var index = userAgent.indexOf("Android")
    var androidVersion = parseFloat(userAgent.slice(index + 8));
    res.version = androidVersion;
    res.type = 'android'
  }

  if (isiOS) {
    res.type = 'ios'
    res.version = '';
  }
  
  return res;
}

//将base64转换为二进制文件
export function dataURItoBlob(dataURI, callback) {
  var byteString = atob(dataURI.split(',')[1]);
  var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
  var ab = new ArrayBuffer(byteString.length);
  var ia = new Uint8Array(ab);
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
  return callback(new Blob([ab], {type: mimeString}));
}

//删除数组中的某一项元素
export function removeArray(array,val) {
  var index = array.indexOf(val);
  if (index > -1) {
    array.splice(index, 1);
  }
  return array;
}


// 数字转为千分位格式
export function toThousands(num) {
  var num = (num || 0).toString(), result = '';
  while (num.length > 3) {
      result = ',' + num.slice(-3) + result;
      num = num.slice(0, num.length - 3);
  }
  if (num) { result = num + result; }
  return result;
}